from .base_strategy import BaseStrategy
import backtrader as bt
import indicator.MyTTIndicator as Mytt

###
# MACD 金叉死叉进行交易。
# 金叉做多，死叉开空
# 固定2%止损，固定10根k线后止盈
# #
class MyStrategy(BaseStrategy):
    params = (
        ('fast_period', 12),
        ('slow_period', 26),
        ('signal_period', 9),
        ('stop_loss_percent', 0.02),  # 2% 止损
        ('take_profit_bars', 10),     # 10 根 K 线后止盈
    )
 
    def __init__(self):
        super().__init__()

        self.init_indicators()

        # 记录开仓价格和日期
        self.buy_price = None
        self.sell_price = None
        self.buy_date = None
        self.sell_date = None
        
        # 跟踪订单状态
        self.order = None
    
    def init_indicators(self):
        """在此定义指标 (EMA/MACD/RSI等)"""
        # 初始化 MACD 指标
        self.macd = bt.indicators.MACD(
            self.data.close,
            period_me1=self.p.fast_period,
            period_me2=self.p.slow_period,
            period_signal=self.p.signal_period
        )





    def notify_order(self, order):
        super().notify_order(order)

        if order.status in [order.Submitted, order.Accepted]:
            # 订单已提交/接受 - 不做任何操作
            return
        
        # 重置订单
        self.order = None

    def next(self):
        super().next()

        # 检查是否已经持有仓位
        if not self.position:
            # 金叉买入信号（DIF 上穿 DEA）
            if self.macd.macd[0] > self.macd.signal[0] and self.macd.macd[-1] <= self.macd.signal[-1]:
                self.order = self.buy()
                self.buy_price = self.data.close[0]
                self.buy_date = self.data.datetime.date(0)
            # 死叉卖出信号（DIF 下穿 DEA）
            elif self.macd.macd[0] < self.macd.signal[0] and self.macd.macd[-1] >= self.macd.signal[-1]:
                self.order = self.sell()
                self.sell_price = self.data.close[0]
                self.sell_date = self.data.datetime.date(0)
        else:
            current_price = self.data.close[0]
            
            # 止损逻辑
            # if self.position.size > 0:  # 多头仓位止损
            #     if (self.buy_price - current_price) / self.buy_price >= self.p.stop_loss_percent:
            #         self.order = self.sell()
            # elif self.position.size < 0:  # 空头仓位止损
            #     if (current_price - self.sell_price) / self.sell_price >= self.p.stop_loss_percent:
            #         self.order = self.buy()
            
            # 止盈逻辑（固定 10 根 K 线后平仓）
            if self.position.size > 0:  # 多头仓位止盈
                if (self.data.datetime.date(0) - self.buy_date).days >= self.p.take_profit_bars:
                    self.order = self.sell()
            elif self.position.size < 0:  # 空头仓位止盈
                if (self.data.datetime.date(0) - self.sell_date).days >= self.p.take_profit_bars:
                    self.order = self.buy()